package com.lazason.wib4android;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import weibo4andriod.Comment;
import weibo4andriod.Paging;
import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;
import com.lazason.wib4android.BasicWib.TimeLineTask;

public class PostCommentActivity extends BasicWib implements OnClickListener {
    
	 private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	 private static final int REQ_CODE_PICTURES = 1000;
	 private static final int REQ_CODE_CAMERA = 1001;
	 private String photoTemp;
	    private ArrayList<String> matches;
	    private EditText editText;
	    TextView sucess ;
	    private Button post;  
	    private String cachePaht; 
	    private ProgressDialog m_ProgressDialog = null; 
	    private Runnable postThread;  
	    private String weiboId;
	    private String username;
	    private String profile;
	    private String createdAt;
	    String picture;
	    String weiboText;
	    Thread thread;
	    ImageView weibo_profile;
	    ImageView comment_picture;
	    ImageView comment_retweetedThumbnailPic;
	    TextView weibo_username;
	    TextView weibo_comment_repost;
	    TextView weibo_createdTime;
	    TextView comment_weibo;
	    TextView comment_retweetedText;
	    AsyncImageLoader asyncImageLoader;
	    /**
	     * Called with the activity is first created.
	     */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        super.initActivity(savedInstanceState,R.layout.comments);
	        MyApplication.getInstance().addActivity(this);
	        // Inflate our UI from its XML layout description.
	        cachePaht = this.getExternalCacheDir().toString();
	        // Get display items for later interaction
	        weiboId = this.getIntent().getStringExtra("id"); 
	        username = this.getIntent().getStringExtra("username"); 
	        profile = this.getIntent().getStringExtra("profile"); 
	        createdAt = this.getIntent().getStringExtra("created_at"); 
	        picture = this.getIntent().getStringExtra("picture"); 
	        weiboText = this.getIntent().getStringExtra("weibo"); 
	        weibo_profile = (ImageView)findViewById(R.id.weibo_profile);
	        Util.setMode4View(this, weibo_profile);
	        
	           
	        asyncImageLoader = new AsyncImageLoader();
			Drawable cachedImage = asyncImageLoader.loadDrawable(this, profile,
					"bf" + profile.hashCode(), Thread.MAX_PRIORITY,
					new ImageCallback() {
						public void imageLoaded(Drawable imageDrawable,
								String imageUrl, String id) {

							if (weibo_profile != null && imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
								weibo_profile.setImageDrawable(imageDrawable);

							}
						}
					});
			if (cachedImage == null) {
				// holder.profile.setImageResource(R.drawable.icon);
				weibo_profile.setImageDrawable(null);
			} else {
				weibo_profile.setImageDrawable(cachedImage);
			}
	        weibo_comment_repost = (TextView)findViewById(R.id.weibo_comment_repost);
	        Util.setMode4View(this, weibo_comment_repost);
	        weibo_username = (TextView)findViewById(R.id.weibo_username);
	        Util.setMode4View(this, weibo_username);
	        weibo_username.setText(username);	    
	        weibo_createdTime = (TextView)findViewById(R.id.weibo_createdTime);
	        Util.setMode4View(this, weibo_createdTime);
	        weibo_createdTime.setText(createdAt);
	        comment_weibo =(TextView)findViewById(R.id.comment_weibo); 
	        Util.setMode4View(this, comment_weibo);
	        comment_weibo.setText(weiboText);
	        comment_retweetedText = (TextView)findViewById(R.id.comment_retweetedText); 
	        Util.setMode4View(this, comment_retweetedText);
	        comment_retweetedText.setText(this.getIntent().getStringExtra("retweetedText"));
	        editText = (EditText) findViewById(R.id.editComment); 
	        
	        editText.clearFocus();
	        post =  (Button) findViewById(R.id.coment_submit);
	        postThread = new Runnable(){  
	            @Override  
	            public void run() {  
	                postWeibo();  
	            }  
	        };  
	       
	        post.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					 
						 thread =  new Thread(null, postThread,"postWeiboThread"); 
						 thread.start();
						 m_ProgressDialog = ProgressDialog.show(PostCommentActivity.this,      
					              "Please wait...", "Uploading data ...", true);  
						
					
				}
				
			});
	        
	       
	        PackageManager pm = getPackageManager();
	        
	        List<ResolveInfo> activities = pm.queryIntentActivities(
	                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);

	        listView = (ListView) findViewById(android.R.id.list);
	        adapter = new MyAdapter(this, data,
					R.layout.comments_item, new String[] { "profile", "username","comment",
							"created_at"}, new int[] {
							R.id.comment_profile,R.id.comment_username, R.id.comment, R.id.comment_createdTime,}, listView);
	        TimeLineTask commentsTask = new TimeLineTask();
	        commentsTask.execute(page);
	        listView.setOnScrollListener(new OnScrollListener() {

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
				
				}

				@Override
				public void onScrollStateChanged(AbsListView paramAbsListView,
						int paramInt) {
					// TODO Auto-generated method stub

				}

			});
	    }

	    /**
	     * Handle the click on the start recognition button.
	     */
	    public void onClick(View v) {
	        if (v.getId() == R.id.btn_speak) {
	            startVoiceRecognitionActivity();
	        }
	    }

	    /**
	     * Fire an intent to start the speech recognition activity.
	     */
	    private void startVoiceRecognitionActivity() {
	        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
	        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
	                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
	        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
	        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	    }

	
	    @Override
		protected void onDestroy() {
			// TODO Auto-generated method stub
			super.onDestroy();
			MyApplication.getInstance().removeActivity(this);
			
		}
	    

	
	    private void postWeibo(){  
	    	Weibo weibo=OAuthConstant.getInstance().getWeibo();
			String text = "";
			try {
				

				Comment comment = weibo.updateComment(editText.getText().toString(), weiboId, null);
				 
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				 
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				 
			} finally{
				 
				Intent intent = new Intent();
				intent.putExtra("id", weiboId);
				intent.putExtra("username", username);
				intent.putExtra("profile", profile);
				intent.putExtra("created_at", createdAt);
				intent.putExtra("picture", picture);
				intent.putExtra("weibo", weiboText);
				intent.setClass(this, PostCommentActivity.class);
				startActivity(intent);
			}
	    }
	    
//	    protected class CommentsTask extends
//		AsyncTask<Integer, Void, List<weibo4andriod.Comment>> {
//
//	protected List<weibo4andriod.Comment> doInBackground(Integer... page) {
//		List<weibo4andriod.Comment> friendsTimeline = null;
//		friendsTimeline = null;
//		try {
//
//			System.out.println("page : " + page[0].intValue());
//			paging.setPage(page[0]);
//
//			friendsTimeline = weibo.getComments(weiboId);
//
//		} catch (WeiboException we) {
//			we.printStackTrace();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//
//		}
//
//		return friendsTimeline;
//	}
//
//	protected void onPostExecute(List<weibo4andriod.Comment> friendsTimeline) {
//		if (friendsTimeline == null) {
//			Toast.makeText(getApplicationContext(), "没有更多的微博",
//					Toast.LENGTH_SHORT).show();
//			isLoading = false;
//			return;
//		}
//		page++;
//		
//		for (weibo4andriod.Comment comment : friendsTimeline) {
//			Map<String, Object> map = Util.comment2Map(comment);
//
//			data.add(map);
//
//		}
//
//		if (isFirstWeibo) {
//			isFirstWeibo = false;
//			listView.setAdapter(adapter);
//			
//		} else {
//			adapter.notifyDataSetChanged();
//		}
//		isLoading = false;
//
//	}
//
//	@Override
//	protected void onPreExecute() {
//		// TODO Auto-generated method stub
//		super.onPreExecute();
//		// listView.addFooterView(layout);
//	}
//	
//	
//	}


@Override
protected void onResume() {
	// TODO Auto-generated method stub
	if (data != null) {
		  adapter = new MyAdapter(this, data,
					R.layout.comments_item, new String[] { "profile", "username","comment",
							"created_at"}, new int[] {
							R.id.comment_profile,R.id.comment_username, R.id.comment, R.id.comment_createdTime,}, listView);

		int lastItem = listView.getFirstVisiblePosition();

		listView.setAdapter(adapter);
		listView.setSelection(lastItem);
	}
//	if(window==null){
//		Timer timer = new Timer();  
//        timer.schedule(new initPopupWindow(), 100);  
//		}
	super.onResume();
}

@Override
protected void addData(List list) {
	
	for (Object comment : list) {
		if(comment instanceof weibo4andriod.Comment){
			Map<String, Object> map = Util.comment2Map((weibo4andriod.Comment)comment);

		MyApplication.data.add(map);
		}

	}
}

@Override
protected List readTimeline(int arg) throws WeiboException {
	// TODO Auto-generated method stub
	 

	 

	return weibo.getComments(weiboId);
}

@Override
void refresh() {
	// TODO Auto-generated method stub
	
}
}